/**
 * Created by FreezeSoul on 2017/7/18.
 */
define(
    ["app/core/base",
        "app/core/util",
        "../echartsMeta",
        "jquery",
        "underscore",
        'JSONParse',
        'loglevel',
        "echarts"
    ],
    function (Chart, Util, Meta, $, _, JSON, log, ec) {

        var property = {
            name: '通用属性',
            config: "property",
            option: [{
                group: '基础',
                id: 'HUAN_XING_CHU_SHI_ZHI',
                name: '默认值',
                enable: false,
                type: 'number',
                value: 0.5,
                default: 0.5,
                tooltip: '环形默认值'
            }, {
                group: '基础',
                id: '668a30ff-7c23-4fb4-9491-df4829d269f9',
                name: '标题颜色',
                enable: false,
                type: 'color',
                value: '#01CD9A',
                default: '#01CD9A',
                link: 'title.textStyle.color',
                tooltip: '标题文字的颜色'
            }, {
                group: '基础',
                id: '97876db5-f8e1-49e0-aa57-af226449e57d',
                name: '标题大小',
                enable: false,
                type: 'number',
                value: 30,
                default: 30,
                link: 'title.textStyle.fontSize',
                tooltip: '标题文字的字体大小'
            }, {
                group: '基础',
                id: '12330ff-7c23-4fb4-9491-df4829d26123',
                name: '控件颜色',
                enable: false,
                type: 'color',
                value: '#01CD9A',
                default: '#01CD9A',
                link: function (option) {
                    var _this = this;
                    var color = ['#01CD9A'];
                    if (_this.enable) {
                        color = [_this.value];
                    }
                    Util.setOption("color", color, option);
                },
                tooltip: '控件背景颜色'
            }].concat([
                {
                    group: '序列',
                    id: 'f53a0a43-6d1b-43e0-b514-122a8b155ece',
                    name: '序列',
                    type: 'group',
                    items: [],
                    option: [
                        {
                            id: '17994381-e1fe-4551-a852-a5a0571ed891',
                            name: '序列绑定',
                            enable: true,
                            type: 'textBinding',
                            dataset: '',
                            ctype: 'measure',//列类型，支持 all,dimension,measure
                            column: {},
                            tooltip: '序列绑定设置，与数据集关系'
                        },
                        {
                            id: 'a320684c-8ca5-49f0-aab7-853e0fde9e5c',
                            name: '过滤列名称',
                            enable: false,
                            type: 'text',
                            value: '',
                            default: '',
                            tooltip: '绑定数据集，客户端过滤字段列名称'
                        },
                        {
                            id: '96f30ae6-6fe0-4faa-8b7f-a302a49a0434',
                            name: '过滤列默认值',
                            enable: false,
                            type: 'text',
                            value: '',
                            default: '',
                            tooltip: '绑定数据集，客户端过滤字段默认值'
                        },
                        {
                            id: 'f3f26cc8-3764-4f0a-8180-a9f88668420c',
                            name: '饼图半径设置',
                            enable: false,
                            type: 'text',
                            value: '55%,75%',
                            link: function (option) {
                                var _this = this;
                                var radius = ['55%', '75%']
                                if (_this.enable) {
                                    var radiusArr = _this.value.split(',');

                                    if (radiusArr.length >= 2) {
                                        radius = $.parseJSON('["' + radiusArr[0] + '","' + radiusArr[1] + '"]');
                                    }
                                }
                                Util.setOption("radius", radius, option);
                            },
                            tooltip: '饼图显示面积的半径设置'
                        }
                    ],
                    link: 'series',
                    tooltip: '字段说明:<br/>分组控件，支持动态扩展，内部可增加支持的类型属性'
                }
            ]).concat($.extend(true, [], Meta.otherProperties)),
            //需要针对组件映射属性至组件Option
            MapOption: function (option) {
                Util.linkOption(this.option, option);
            }
        };

        var pie = Chart.extend({
            constructor: function (layout) {
                this._layout = layout;
                this._lastdata = null;
                this._container = null;
                this._chart = null;
                this._option = {
                    Binding: [],
                    Events: [],
                    Extend: $.extend(true, {}, property),
                    Option: {
                        color: ['#01CD9A'],
                        title: {
                            text: '0%',
                            textStyle: {
                                color: '#01CD9A',
                                fontSize: 30,
                                fontWeight: 'bold',
                                fontFamily: '华文细黑',
                            },
                            x: 'center',
                            y: 'center'
                        },
                        visualMap: [{
                            show: false,
                            dimension: 1,
                            seriesIndex: 0,
                            min: 0,
                            max: 0,
                            inRange: {
                                colorAlpha: [0, 1]
                            }
                        }],
                        series: [{
                            type: 'pie',
                            radius: ['55%', '75%'],
                            center: ['50%', '50%'],
                            silent: true,
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]
                        }]
                    }
                };
            },
            init: function (element) {
                try {
                    this._container = element;
                    this._chart = ec.init(element, null, {
                        renderer: 'canvas'
                    });
                    this._bindEvent();
                } catch (e) {
                    log.error(e);
                }
            },
            _bindEvent: function () {
                var _this = this;
                if (!this._filterDataHandle) {
                    this._filterDataHandle = function (params) {
                        _this.filterDataHandle.call(_this, params);
                    };
                }
                this._layout.removeListener("filterData", this._filterDataHandle);
                this._layout.addListener("filterData", this._filterDataHandle);
            },
            filterDataHandle: function (params) {
                var _this = this;
                var flag = false;
                var seriesItems = _.findWhere(_this._option.Extend.option, {type: 'group'});
                $.each(seriesItems.items, function (i, item) {
                    var filterColumn = _.findWhere(item.option, {name: '过滤列名称'});
                    var filterValue = _.findWhere(item.option, {name: '过滤列默认值'});

                    if (filterColumn && filterValue
                        && filterColumn.enable && filterValue.enable
                        && filterColumn.value !== "" && filterValue.value !== ""
                    ) {
                        for (var prop in params) {
                            if (!params.hasOwnProperty(prop)) continue;
                            if (filterColumn.value === prop) {
                                filterValue.value = params[prop];
                                flag = true;
                            }
                        }
                    }
                });
                if (flag && _this._lastdata) {
                    _this.setData(_this._lastdata);
                }
            },
            example: function () {
                try {
                    this._chart.setOption(this._option.Option, true);
                } catch (e) {
                    log.error(e);
                }
            },
            _initValue: function () {
                var count = 60;
                var percent = 0.0;
                var initValue = _.findWhere(this._option.Extend.option, {id: "HUAN_XING_CHU_SHI_ZHI"});
                if (initValue && initValue.enable && initValue.value && (initValue.value >= 0 && initValue.value <= 1)) {
                    percent = initValue.value;
                } else {
                    return;
                }
                var visibleCount = count * percent;
                var data = [];
                for (var i = 0; i < visibleCount; i++) {
                    data.push([1, i]);
                }
                for (var j = visibleCount; j < count; j++) {
                    data.push([1, 0]);
                }
                if (this._option.Option.title) {
                    this._option.Option.title.text = Math.ceil(percent * 100) + '%';
                }
                if (this._option.Option.visualMap && this._option.Option.visualMap.length > 0) {
                    this._option.Option.visualMap[0].max = visibleCount;
                }
                if (this._option.Option.series && this._option.Option.series.length > 0) {
                    this._option.Option.series[0].data = data;
                }
            },
            _readProperty: function () {
                try {
                    if (!this._option.Extend) return;
                    Util.deepMapOption(property, this._option.Extend, this._option.Option);
                } catch (e) {
                    log.error(e);
                }
            },
            //TODO:需要重写的部分
            _bindData: function (data) {
                var tables = data;
                var _this = this;


                //根据每个option自行查找，可通过id或name，这里因为只有一个group,因此通过type查找
                var seriesItems = _.findWhere(this._option.Extend.option, {type: 'group'});

                //清除工作
                if (seriesItems.items.length > 0) {
                    var item = seriesItems.items[0];
                    var bindProperty = _.findWhere(item.option, {type: 'textBinding'});
                    if (!bindProperty) return;

                    var dataSetCode = bindProperty.dataset;
                    //var dimensionCode = bindProperty.dimension.ColumnCode;
                    var measureCode = bindProperty.column.ColumnCode;

                    //var nameProperty = _.findWhere(item.option, {name: '序列名称'});

                    if (dataSetCode && measureCode) {
                        var table = tables[dataSetCode];
                        var binding = _.findWhere(_this._option.Binding, {DataSetCode: dataSetCode});
                        //var dimension = _.findWhere(binding.Dimensions, {Code: dimensionCode}).Column;
                        var measure = _.findWhere(binding.Measures, {Code: measureCode}).Column;
                        var dataArray = [];

                        table = _this._filterTable(item.option, table);
                        if (table && table.length > 0) {
                            var row = table[0];
                            var count = 60;
                            var value = row[measure];
                            if (!$.isNumeric(value) || value > 1) {
                                log.error(" value error " + value);
                                return;
                            }
                            var percent = parseFloat(value);
                            var visibleCount = count * percent;
                            for (var i = 0; i < visibleCount; i++) {
                                dataArray.push([1, i]);
                            }
                            for (var j = visibleCount; j < count; j++) {
                                dataArray.push([1, 0]);
                            }
                        }
                        if (this._option.Option.title) {
                            this._option.Option.title.text = Math.ceil(percent * 100) + '%';
                        }

                        if (this._option.Option.visualMap && this._option.Option.visualMap.length > 0) {
                            this._option.Option.visualMap[0].max = visibleCount;
                        }

                        if (_this._option.Option.series.length > 0) {
                            _this._option.Option.series[0].type = 'pie';
                            //_this._option.Option.series[0].name = nameProperty.value;
                            _this._option.Option.series[0].data = dataArray;

                        } else {
                            _this._option.Option.series.push(
                                {
                                    //name: nameProperty.value,
                                    selectedMode: 'single',
                                    type: 'pie',
                                    radius: ['55%', '75%'],
                                    center: ['50%', '50%'],
                                    silent: true,
                                    labelLine: {
                                        normal: {
                                            show: false
                                        }
                                    },
                                    data: dataArray
                                });
                        }
                    }
                }
            },
            _filterTable: function (option, table) {
                var filterColumn = _.findWhere(option, {name: '过滤列名称'});
                var filterValue = _.findWhere(option, {name: '过滤列默认值'});

                if (filterColumn && filterValue
                    && filterColumn.enable && filterValue.enable
                    && filterColumn.value !== "" && filterValue.value !== ""
                ) {
                    var tableCopy = _.map(table, _.clone);
                    return _.filter(tableCopy, function (row) {
                        return row[filterColumn.value] === filterValue.value;
                    });
                }
                return table;
            },
            setData: function (data) {
                try {
                    this._lastdata = data;

                    this._readProperty();

                    this._initValue();

                    if (data
                        && this._option.Binding
                        && this._option.Binding.length > 0
                        && this._option.Extend) {

                        this._bindData(data);

                        this._readProperty();
                    }
                    var _this = this;
                    setTimeout(function () {
                        _this._chart.setOption(_this._option.Option, true);
                    });
                    //Util.setEChartsMeta(this, this._container, this._option.Extend.option);
                } catch (e) {
                    log.error(e);
                }
            },
            setOption: function (option) {
                try {
                    return this._option = $.extend(true, {}, option);
                } catch (e) {
                    log.error(e);
                }
            },
            getOption: function () {
                try {
                    this._readProperty();
                } catch (e) {
                    log.error(e);
                }
                return this._option;
            },
            setTheme: function (theme) {
                try {
                    this._chart.setTheme(theme);
                } catch (e) {
                    log.error(e);
                }
            },
            resize: function () {
                try {
                    this._chart.resize();
                } catch (e) {
                    log.error(e);
                }
            },
            showLoading: function () {
                try {
                    if (this._layout && this._layout.showLoading) {
                        this._layout.showLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            hideLoading: function () {
                try {
                    if (this._layout && this._layout.hideLoading) {
                        this._layout.hideLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            dispose: function () {
                try {
                    this._chart.dispose();
                    this._layout.removeListener("filterData", this._filterDataHandle);
                } catch (e) {
                    log.error(e);
                }
            },
            getElement: function () {
                return this._container;
            },
            getChart: function () {
                return this._chart;
            }
        });

        return {
            Chart: pie,
            Property: property
        };
    });
